const db = require('../db/index.js')

function addHomework(ctx) {
  return new Promise(resolve => {
    let msg = ''
    db.homework.insert({
      ...ctx.request.body,
      path: ctx.request.files.file.path.match(/upload_.+\..*/)[0],
      originName: ctx.request.files.file.name,
      level: '',
      comment: '',
      created: Date.now()
    })
    ctx.response.status = 200
    msg = '添加成功'
    ctx.response.body = {
      msg
    }
    resolve()
  })
}

function updateHomework(ctx) {
  return new Promise(resolve => {
    let msg = ''
    const _id = ctx.params.id
    const data = ctx.request.body
    db.homework.update({ _id }, { $set: { ...data, updated: Date.now() }}, {}, err => {
      if (!err) {
        ctx.response.status = 200
        msg = '修改成功'
      } else {
        ctx.response.status = 400
        msg = err || '修改失败'
      }
      ctx.response.body = {
        msg
      }
      resolve()
    })
  })
}

function getHomework(ctx) {
  return new Promise(resolve => {
    db.homework.findOne({ _id: ctx.params.id }, function(err, data) {
      if (err) {
        ctx.response.status = 400
        ctx.response.body = err
        return
      }
      ctx.response.status = 200
      ctx.response.body = data
      resolve()
    })
  })
}

function getHomeworkListUtil(query = {}) {
  return new Promise(resolve => {
    db.homework.find(query, function(err, data) {
      if (err) {
        return Promise.reject(err)
      }
      resolve(data)
    })
  })
}

async function getHomeworkList(ctx) {
  const data = await getHomeworkListUtil()
  ctx.response.status = 200
  ctx.response.body = data
}

module.exports = {
  addHomework,
  updateHomework,
  getHomework,
  getHomeworkList,
  getHomeworkListUtil
}
